package com.zzh.framework;

import com.zzh.framework.protocol.http.HttpClient;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.List;

/**
 * @author：zhangzhanheng
 * @createTime: 2021/8/3  8:01 下午
 * @desc: 代理对象
 * @version: 1.0.0
 **/
public class ProxyFactory {

    @SuppressWarnings("unchecked")
    public static <T> T getProxy(final Class interfaceClass) {
        return (T) Proxy.newProxyInstance(interfaceClass.getClassLoader(), new Class[]{interfaceClass}, new InvocationHandler() {
            @Override
            public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                //代理逻辑
                //todo:用工厂加抽象类 来解决切换http和duboo
                HttpClient httpClient = new HttpClient();
                Invocation invocation = new Invocation(interfaceClass.getName(),method.getName(),method.getParameterTypes(),args);
                List<URL> urls = RemoteMapRegister.get(interfaceClass.getName());
                URL url = LoadBalance.random(urls);
                String result = httpClient.send(url.getHostname(), url.getProt(), invocation);
                return result;
            }
        });
    }
}
